package cn.his.gateway.filter;

import cn.his.util.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: czm
 * @Date: 2022/04/14/15:29
 * @Description:用于请求的全局过滤器
 */
@Component
public class GatewayRequestFilter implements GlobalFilter, Ordered {

    //@Autowired
    //private RedisTemplate<String,String> redisTemplate;

    //@Autowired
    //private AuthFegin authFegin;




    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求与响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //放行不需要登录路由
        //String uri = request.getURI().getPath();
        //if (uri.startsWith("/tqw/auth/") || uri.equals("/tqw/item/itemCat/findItemCatList/3")
        //    || uri.startsWith("/tqw/es/") || uri.startsWith("/tqw/item/itemDesc") || uri.equals("/tqw/item/file/upload")){
        //    return chain.filter(exchange);
        //}

        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
            return chain.filter(exchange);
        }
        String substringToken = token.substring(7);
        System.out.println(substringToken);
        try {
            JWTUtil.verify(substringToken);
        }catch (Exception e){
            e.printStackTrace();
        }

        //Long expire = redisTemplate.getExpire(substringToken);
        //if (expire!=-2){
        //        //    boolean expired = JWTUtil.isExpired(token);
        //        //    if (!expired){
        //        //        return chain.filter(exchange);
        //        //    }
        //        //    String s = redisTemplate.opsForValue().get(token);
        //        //    String newToken = authFegin.refreshToken(Integer.valueOf(s));
        //        //    redisTemplate.opsForValue().set(newToken,s, Duration.ofHours(3));
        //        //    response.getHeaders().add("token",newToken);
        //        //    response.getHeaders().set("Access-Control-Expose-Headers","token");
        //        //    response.setComplete();
        //        //    return chain.filter(exchange);
        //        //}
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setComplete();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
